function [data,nbr_frames] = load_tiff_exp(userID, mouse_id, ExpID, dvh ,fnames)
% READ TIFF STACK FILES
% Read tiff stack files

ud = get(dvh.hf, 'UserData');
rootDir = ud.rdata_dir;
IJpluginDir ='C:\Program Files\MBF_ImageJ';

%% select animal folder
folder2 = [rootDir userID '\' mouse_id '\'];
disp([ 'folder ' folder2])
disp(['Exp ', num2str(ExpID), ' , num of folders = ' num2str(length(fnames))]);

%% init data
whos fnames
for j=1:length(fnames)
    
    disp(fnames{1});
    folder3=fullfile(folder2,fnames{j});
        
    GrabInfo_file = dir([folder3 '/*GRABinfo.mat']);
    load(fullfile(folder3,GrabInfo_file.name));   
    
    FramesPerFile=GRABinfo.loggingFramesPerFile;
    slices=GRABinfo.stackNumSlices;

    filenames = dir([folder3 '/*.tif']);
    filenames = {filenames.name};
    
    x_pixels=GRABinfo.scanPixelsPerLine; 
    y_pixels=GRABinfo.scanLinesPerFrame;
    
    nbr_frames(j) = FramesPerFile*length(filenames);
end

number_of_frames_total=sum(nbr_frames);
frames_per_slice = round(number_of_frames_total/slices);

data = cell(1,slices);
for j=1:slices
    data{j} = zeros(x_pixels, y_pixels, frames_per_slice, 'uint16');
end
    
sliceframes=ones(1,4);
%% Open the slices in the tiff 
for j=1:length(fnames)

    folder3=fullfile(folder2,fnames{j});
    folder3=folder3(~isspace(folder3));
        
    GrabInfo_file = dir([folder3 '/*GRABinfo.mat']);
    load(fullfile(folder3,GrabInfo_file.name));   

    filenames = dir([folder3 '/*.tif']);
    filenames = {filenames.name};

        for ss=1:slices
           
            clear a
            x_pixels=GRABinfo.scanPixelsPerLine; 
            y_pixels=GRABinfo.scanLinesPerFrame; 
            nframes=GRABinfo.acqNumFrames;
            FramesPerFile=GRABinfo.loggingFramesPerFile;
%             disp([' Frames per file = ' , num2str(FramesPerFile)]);
            if (ss==1) display(['Opening Tiff : ', fnames{j}]); end

         try
            if GRABinfo.loggingFramesPerFile==Inf
                disp('inf')
                a=load_multistacktiff(folder3,filenames,x_pixels,y_pixels,nframes,ss,slices,GRABinfo.acqNumFrames);
            else
                a=load_multistacktiff(folder3,filenames,x_pixels,y_pixels,nframes,ss,slices,FramesPerFile);
            end
            
            if (ss==slices) display('Tiff opened'); end

      
         catch ME
             display(ME.message)
             display(['Error in ' 'File: ' num2str(j) 'Slice: ' num2str(ss)])
             keyboard    
         end
         asize = size(a,3);
         data{ss}(:,:,sliceframes(ss):(sliceframes(ss)+ asize)-1) = a;
         sliceframes(ss)=sliceframes(ss)+ asize;
        end
end
sliceframes=sliceframes-1;
for ss=1:slices
    data{ss}=data{ss}(:,:,1:sliceframes(ss));
end
disp('data size    Frames/slice')
disp([size(data{1},3) sliceframes]);
nbr_frames=sliceframes(1);

